<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"yoursite.com","root":"/blog/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="安卓开发图片压缩一直是一个头痛的问题，一不小心就会oom。我对一个github上的库就行了简单的改写，把代码记录下来，自己也梳理了下图片压缩的过程。  本文的代码参考自github项目 Compressor，我只是进行了我认为需要的改动 本文的代码 尺寸压缩 尺寸压缩也就是按比例压缩尺寸，当我们需要显示图片时，控件加载的是bitmap,而bitmap的大小主要和尺寸和图片格式有关，这时候我们不需">
<meta property="og:type" content="article">
<meta property="og:title" content="仿写一个android图片压缩工具">
<meta property="og:url" content="http://yoursite.com/2017/12/28/compress/index.html">
<meta property="og:site_name" content="二松同学">
<meta property="og:description" content="安卓开发图片压缩一直是一个头痛的问题，一不小心就会oom。我对一个github上的库就行了简单的改写，把代码记录下来，自己也梳理了下图片压缩的过程。  本文的代码参考自github项目 Compressor，我只是进行了我认为需要的改动 本文的代码 尺寸压缩 尺寸压缩也就是按比例压缩尺寸，当我们需要显示图片时，控件加载的是bitmap,而bitmap的大小主要和尺寸和图片格式有关，这时候我们不需">
<meta property="article:published_time" content="2017-12-28T08:59:57.000Z">
<meta property="article:modified_time" content="2020-06-23T03:08:32.948Z">
<meta property="article:author" content="二松">
<meta property="article:tag" content="android">
<meta property="article:tag" content="压缩">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://yoursite.com/2017/12/28/compress/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-Hans'
  };
</script>

  <title>仿写一个android图片压缩工具 | 二松同学</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">二松同学</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">拥有梦想只是一种智力，实现梦想才是一种能力</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/12/28/compress/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
      <meta itemprop="name" content="二松">
      <meta itemprop="description" content="good good study day day up.">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="二松同学">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          仿写一个android图片压缩工具
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-12-28 16:59:57" itemprop="dateCreated datePublished" datetime="2017-12-28T16:59:57+08:00">2017-12-28</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-06-23 11:08:32" itemprop="dateModified" datetime="2020-06-23T11:08:32+08:00">2020-06-23</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/%E6%8A%80%E6%9C%AF%E5%8D%9A%E5%AE%A2/" itemprop="url" rel="index"><span itemprop="name">技术博客</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <blockquote>
<p>安卓开发图片压缩一直是一个头痛的问题，一不小心就会<code>oom</code>。<br>我对一个<code>github</code>上的库就行了简单的改写，把代码记录下来，自己也梳理了下图片压缩的过程。</p>
</blockquote>
<p><a href="https://github.com/zetbaitsu/Compressor" target="_blank" rel="noopener">本文的代码参考自github项目 Compressor，我只是进行了我认为需要的改动</a></p>
<p><a href="https://github.com/songsongtao/fast_code/tree/master/fastlib/src/main/java/com/song/fast/compressor" target="_blank" rel="noopener">本文的代码</a></p>
<h2 id="尺寸压缩"><a href="#尺寸压缩" class="headerlink" title="尺寸压缩"></a>尺寸压缩</h2><blockquote>
<p>尺寸压缩也就是按比例压缩尺寸，当我们需要显示图片时，控件加载的是<code>bitmap</code>,而<code>bitmap</code>的大小主要和尺寸和图片格式有关，这时候我们不需要进行质量压缩</p>
</blockquote>
<ul>
<li><p>计算采样比(图片压缩比例)</p>
  <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">calculateInSampleSize</span><span class="params">(BitmapFactory.Options options, <span class="keyword">int</span> reqWidth, <span class="keyword">int</span> reqHeight)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 获得原始宽高</span></span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> height = options.outHeight;</span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> width = options.outWidth;</span><br><span class="line">    <span class="comment">//默认为1(不压缩)</span></span><br><span class="line">    <span class="keyword">int</span> inSampleSize = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (height &gt; reqHeight || width &gt; reqWidth) &#123;</span><br><span class="line">        <span class="comment">//压缩到宽高都小于我们要求的大小</span></span><br><span class="line">        <span class="keyword">while</span> ((height / inSampleSize) &gt;= reqHeight || (width / inSampleSize) &gt;= reqWidth) &#123;</span><br><span class="line">            <span class="comment">//android内部只会取2的倍数，也就是一半一半的压缩</span></span><br><span class="line">            inSampleSize *= <span class="number">2</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> inSampleSize;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p>压缩尺寸</p>
  <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">static</span> Bitmap <span class="title">decodeSampledBitmapFromFile</span><span class="params">(File imageFile, <span class="keyword">int</span> reqWidth, <span class="keyword">int</span> reqHeight)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">    BitmapFactory.Options options = <span class="keyword">new</span> BitmapFactory.Options();</span><br><span class="line">    <span class="comment">//设置inJustDecodeBounds=true,时BitmapFactory加载图片不返回bitmap,只返回信息,减少内存开销</span></span><br><span class="line">    options.inJustDecodeBounds = <span class="keyword">true</span>;</span><br><span class="line">    <span class="comment">//相当于加载空图片获取尺寸信息</span></span><br><span class="line">    BitmapFactory.decodeFile(imageFile.getAbsolutePath(), options);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//用我们上面的方法计算压缩比例</span></span><br><span class="line">    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//设置inJustDecodeBounds=false,返回bitmap</span></span><br><span class="line">    options.inJustDecodeBounds = <span class="keyword">false</span>;</span><br><span class="line">    Bitmap scaledBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), options);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//把图片旋转成正确的方向</span></span><br><span class="line">    ExifInterface exif = <span class="keyword">new</span> ExifInterface(imageFile.getAbsolutePath());</span><br><span class="line">    <span class="keyword">int</span> orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, <span class="number">0</span>);</span><br><span class="line">    Matrix matrix = <span class="keyword">new</span> Matrix();</span><br><span class="line">    <span class="keyword">if</span> (orientation == <span class="number">6</span>) &#123;</span><br><span class="line">        matrix.postRotate(<span class="number">90</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (orientation == <span class="number">3</span>) &#123;</span><br><span class="line">        matrix.postRotate(<span class="number">180</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (orientation == <span class="number">8</span>) &#123;</span><br><span class="line">        matrix.postRotate(<span class="number">270</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//复制一份旋转后的bitmap后返回</span></span><br><span class="line">    scaledBitmap = Bitmap.createBitmap(scaledBitmap, <span class="number">0</span>, <span class="number">0</span>, scaledBitmap.getWidth(),</span><br><span class="line">            scaledBitmap.getHeight(), matrix, <span class="keyword">true</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> scaledBitmap;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="质量压缩"><a href="#质量压缩" class="headerlink" title="质量压缩"></a>质量压缩</h2><blockquote>
<p>质量压缩代码比较简单但要注意非常耗时</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> ByteArrayOutputStream <span class="title">compressBitmapSize</span><span class="params">(Bitmap bitmap, Bitmap.CompressFormat compressFormat,</span></span></span><br><span class="line"><span class="function"><span class="params">                                                           <span class="keyword">int</span> defaultQuality, <span class="keyword">long</span> maxSize)</span> </span>&#123;</span><br><span class="line">       ByteArrayOutputStream baos = <span class="keyword">new</span> ByteArrayOutputStream();</span><br><span class="line">       <span class="keyword">int</span> quality = defaultQuality;</span><br><span class="line">       bitmap.compress(compressFormat, quality, baos);</span><br><span class="line">       <span class="comment">//当大于我们指定的大小时，我就继续压缩</span></span><br><span class="line">       <span class="keyword">while</span> (baos.toByteArray().length / <span class="number">1024</span> &gt; maxSize) &#123;</span><br><span class="line">           <span class="keyword">if</span> (quality &lt;= <span class="number">10</span>) &#123; <span class="comment">//压缩比例要大于0</span></span><br><span class="line">               <span class="keyword">break</span>;</span><br><span class="line">           &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">               baos.reset();</span><br><span class="line">               quality -= <span class="number">10</span>;</span><br><span class="line">               <span class="comment">//quality 表示压缩多少 100 表示不压缩</span></span><br><span class="line">               bitmap.compress(compressFormat, quality, baos);</span><br><span class="line">           &#125;</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       <span class="keyword">return</span> baos;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<h2 id="完整的压缩工具类"><a href="#完整的压缩工具类" class="headerlink" title="完整的压缩工具类"></a>完整的压缩工具类</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ImageUtil</span> </span>&#123;</span><br><span class="line">    <span class="comment">//compress main way</span></span><br><span class="line">    <span class="function"><span class="keyword">static</span> File <span class="title">compressImage</span><span class="params">(File imageFile, <span class="keyword">long</span> size, <span class="keyword">int</span> reqWith, <span class="keyword">int</span> reqHeight, Bitmap.CompressFormat compressFormat,</span></span></span><br><span class="line"><span class="function"><span class="params">                              <span class="keyword">int</span> quantity, String destinationPath)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        FileOutputStream fileOutputStream = <span class="keyword">null</span>;</span><br><span class="line">        File file = <span class="keyword">new</span> File(destinationPath).getParentFile();</span><br><span class="line">        <span class="keyword">if</span> (!file.exists()) &#123;</span><br><span class="line">            file.mkdirs();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            fileOutputStream = <span class="keyword">new</span> FileOutputStream(destinationPath);</span><br><span class="line">            <span class="comment">//先压缩尺寸，防止内存溢出</span></span><br><span class="line">            Bitmap bitmap = decodeSampledBitmapFromFile(imageFile, reqWith, reqHeight);</span><br><span class="line">            <span class="comment">//ByteArrayOutputStream 不需要关闭</span></span><br><span class="line">            <span class="comment">//压缩尺寸</span></span><br><span class="line">            ByteArrayOutputStream baos = compressBitmapSize(bitmap, compressFormat, quantity, size);</span><br><span class="line">        fileOutputStream.write(baos.toByteArray());</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (fileOutputStream != <span class="keyword">null</span>) &#123;</span><br><span class="line">                fileOutputStream.flush();</span><br><span class="line">                fileOutputStream.close();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> File(destinationPath);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//按照比例压缩图片</span></span><br><span class="line">    <span class="function"><span class="keyword">static</span> Bitmap <span class="title">decodeSampledBitmapFromFile</span><span class="params">(File imageFile, <span class="keyword">int</span> reqWidth, <span class="keyword">int</span> reqHeight)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        BitmapFactory.Options options = <span class="keyword">new</span> BitmapFactory.Options();</span><br><span class="line">        <span class="comment">//just need size</span></span><br><span class="line">        options.inJustDecodeBounds = <span class="keyword">true</span>;</span><br><span class="line">        BitmapFactory.decodeFile(imageFile.getAbsolutePath(), options);</span><br><span class="line">        <span class="comment">//calculate inSampleSize</span></span><br><span class="line">        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);</span><br><span class="line">        <span class="comment">//real decode bitmap</span></span><br><span class="line">        options.inJustDecodeBounds = <span class="keyword">false</span>;</span><br><span class="line">        Bitmap scaledBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), options);</span><br><span class="line">        <span class="comment">//rotation of the image</span></span><br><span class="line">        ExifInterface exif = <span class="keyword">new</span> ExifInterface(imageFile.getAbsolutePath());</span><br><span class="line">        <span class="keyword">int</span> orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, <span class="number">0</span>);</span><br><span class="line">        Matrix matrix = <span class="keyword">new</span> Matrix();</span><br><span class="line">        <span class="keyword">if</span> (orientation == <span class="number">6</span>) &#123;</span><br><span class="line">            matrix.postRotate(<span class="number">90</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (orientation == <span class="number">3</span>) &#123;</span><br><span class="line">            matrix.postRotate(<span class="number">180</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (orientation == <span class="number">8</span>) &#123;</span><br><span class="line">            matrix.postRotate(<span class="number">270</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        scaledBitmap = Bitmap.createBitmap(scaledBitmap, <span class="number">0</span>, <span class="number">0</span>, scaledBitmap.getWidth(),</span><br><span class="line">                scaledBitmap.getHeight(), matrix, <span class="keyword">true</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> scaledBitmap;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//获取采样（压缩比）</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">calculateInSampleSize</span><span class="params">(BitmapFactory.Options options, <span class="keyword">int</span> reqWidth, <span class="keyword">int</span> reqHeight)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// Raw height and width of image</span></span><br><span class="line">        <span class="keyword">final</span> <span class="keyword">int</span> height = options.outHeight;</span><br><span class="line">        <span class="keyword">final</span> <span class="keyword">int</span> width = options.outWidth;</span><br><span class="line">        <span class="keyword">int</span> inSampleSize = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (height &gt; reqHeight || width &gt; reqWidth) &#123;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">while</span> ((height / inSampleSize) &gt;= reqHeight || (width / inSampleSize) &gt;= reqWidth) &#123;</span><br><span class="line">                inSampleSize *= <span class="number">2</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> inSampleSize;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//压缩尺寸</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> ByteArrayOutputStream <span class="title">compressBitmapSize</span><span class="params">(Bitmap bitmap, Bitmap.CompressFormat compressFormat,</span></span></span><br><span class="line"><span class="function"><span class="params">                                                            <span class="keyword">int</span> defaultQuality, <span class="keyword">long</span> maxSize)</span> </span>&#123;</span><br><span class="line">        ByteArrayOutputStream baos = <span class="keyword">new</span> ByteArrayOutputStream();</span><br><span class="line">        <span class="keyword">int</span> quality = defaultQuality;</span><br><span class="line">        bitmap.compress(compressFormat, quality, baos);</span><br><span class="line">        <span class="keyword">while</span> (baos.toByteArray().length / <span class="number">1024</span> &gt; maxSize) &#123;</span><br><span class="line">            <span class="keyword">if</span> (quality &lt;= <span class="number">10</span>) &#123; <span class="comment">// quality must &gt;0</span></span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                baos.reset();</span><br><span class="line">                quality -= <span class="number">10</span>;</span><br><span class="line">                bitmap.compress(compressFormat, quality, baos);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> baos;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="封装成一个工厂模式工具类"><a href="#封装成一个工厂模式工具类" class="headerlink" title="封装成一个工厂模式工具类"></a>封装成一个工厂模式工具类</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Compressor</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">long</span> maxSize = <span class="number">1024</span>; <span class="comment">//1024kb</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> maxWidth = <span class="number">800</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> maxHeight = <span class="number">800</span>;</span><br><span class="line">    <span class="keyword">private</span> Bitmap.CompressFormat compressFormat = Bitmap.CompressFormat.JPEG;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> quality = <span class="number">80</span>;</span><br><span class="line">    <span class="keyword">private</span> String destinationDirectoryPath;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Compressor</span><span class="params">(Context context)</span> </span>&#123;</span><br><span class="line">        destinationDirectoryPath = context.getCacheDir().getPath() + File.separator + <span class="string">"images"</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Compressor <span class="title">setMaxSize</span><span class="params">(<span class="keyword">long</span> size)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.maxSize = size;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Compressor <span class="title">setMaxWidth</span><span class="params">(<span class="keyword">int</span> maxWidth)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.maxWidth = maxWidth;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Compressor <span class="title">setMaxHeight</span><span class="params">(<span class="keyword">int</span> maxHeight)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.maxHeight = maxHeight;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Compressor <span class="title">setCompressFormat</span><span class="params">(Bitmap.CompressFormat compressFormat)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.compressFormat = compressFormat;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Compressor <span class="title">setQuality</span><span class="params">(<span class="keyword">int</span> quality)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.quality = quality;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Compressor <span class="title">setDestinationDirectoryPath</span><span class="params">(String destinationDirectoryPath)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.destinationDirectoryPath = destinationDirectoryPath;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//压缩到文件</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> File <span class="title">compressToFile</span><span class="params">(File imageFile, String compressedFileName)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> ImageUtil.compressImage(imageFile, maxSize, maxWidth, maxHeight, compressFormat, quality,</span><br><span class="line">                destinationDirectoryPath + File.separator + compressedFileName);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//只压缩尺寸</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Bitmap <span class="title">compressToBitmap</span><span class="params">(File imageFile)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> ImageUtil.decodeSampledBitmapFromFile(imageFile, maxWidth, maxHeight);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h2><blockquote>
<p>推荐大家使用WEBP格式的图片，内存更小(png无损格式很大)而且不会损失透明度(jpg没有透明)</p>
</blockquote>
</li>
<li><p>简单用法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">File file = <span class="keyword">new</span> Compressor(CompressorActivity.<span class="keyword">this</span>)</span><br><span class="line">                      .compressToFile(getExternalCacheDir().getAbsoluteFile(),</span><br><span class="line">                              UUID.randomUUID().toString() + <span class="string">".jpg"</span>);</span><br></pre></td></tr></table></figure></li>
<li><p>指定压缩的参数</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">File file = <span class="keyword">new</span> Compressor(CompressorActivity.<span class="keyword">this</span>)</span><br><span class="line">                     .setMaxWidth(<span class="number">1080</span>)</span><br><span class="line">                     .setMaxHeight(<span class="number">1080</span>)</span><br><span class="line">                     .setQuality(<span class="number">75</span>)</span><br><span class="line">                     .setMaxSize(<span class="number">100</span>)</span><br><span class="line">                     .setCompressFormat(Bitmap.CompressFormat.WEBP)</span><br><span class="line">                     .setDestinationDirectoryPath(getExternalCacheDir().getAbsolutePath())</span><br><span class="line">                     .compressToFile(<span class="keyword">new</span> File(getPath(CompressorActivity.<span class="keyword">this</span>, uri)), UUID.randomUUID().toString() + <span class="string">".webp"</span>);</span><br></pre></td></tr></table></figure></li>
</ul>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blog/tags/android/" rel="tag"># android</a>
              <a href="/blog/tags/%E5%8E%8B%E7%BC%A9/" rel="tag"># 压缩</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2017/12/27/indicator/" rel="prev" title="自己撸一个简单的Viewpager指示器">
      <i class="fa fa-chevron-left"></i> 自己撸一个简单的Viewpager指示器
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2018/04/09/inline/" rel="next" title="kotlin中的内联函数笔记">
      kotlin中的内联函数笔记 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#尺寸压缩"><span class="nav-number">1.</span> <span class="nav-text">尺寸压缩</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#质量压缩"><span class="nav-number">2.</span> <span class="nav-text">质量压缩</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#完整的压缩工具类"><span class="nav-number">3.</span> <span class="nav-text">完整的压缩工具类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#封装成一个工厂模式工具类"><span class="nav-number">4.</span> <span class="nav-text">封装成一个工厂模式工具类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用"><span class="nav-number">5.</span> <span class="nav-text">使用</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="二松"
      src="/blog/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">二松</p>
  <div class="site-description" itemprop="description">good good study day day up.</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">27</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">32</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">二松</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  













<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'forest',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  

</body>
</html>
